<?php
namespace Modules;

use Admin\Models\cost\CostChargeFlow;
use Admin\Models\school\XhschoolInfo;
use Admin\Models\user\XhsysUser;
use Helpers\Main;
use Helpers\Tool;
use Helpers\User;
use Helpers\XhException;
use Admin\Models\user\XhsysUserstud;
use Admin\Models\cost\CostCharge;
use Admin\Models\cost\CostChargeDetail;

class Charge
{

    public static $enum = [
        'bEbook' => [0 => '', 1 => '√'],
        'sourceType' => [1 => '流水', 2 => '姓名', 3 => '手动'],
    ];

    /**
     * 导入缴费明细
     *
     * @param int $year
     * @param int $userId
     * @param float $receivable
     * @param array $extra
     * @throws XhException
     *
     * create by ck 20180914
     */
    public static function importDetail(int $year, int $userId, float $receivable, array $extra = [])
    {
        if ($receivable <= 0) {
            throw new XhException('应缴需大于0');
        }
        $db = Main::getDB();
        try {
            $db->begin();
            $detail = new CostChargeDetail(array_merge([
                'year' => $year,
                'userId' => $userId,
                'receivable' => $receivable
            ], $extra));

            //处理总表
            $charge = CostCharge::getInitObj($year, $userId);
            $charge->receivable += $detail->receivable;
            $charge->chargeNum++;

            //处理到期时间
            if ($detail->serviceEnd) {
                $stud = XhsysUserstud::getInitObj($userId);
                if ($detail->serviceEnd > $stud->iExpireTime) {
                    $stud->iExpireTime = $detail->serviceEnd;
                    if (!$stud->save()) {
                        throw new XhException('学生保存失败：' . $stud->getError());
                    }
                }
            }
            if (!$charge->save()) {
                throw new XhException('保存失败：' . $charge->getError());
            }
            if (!$detail->save()) {
                throw new XhException('详情保存失败：' . $detail->getError());
            }
            $db->commit();
        } catch (XhException $e) {
            $db->rollback();
            throw new XhException($e->getMessage());
        }
    }

    /**
     * 导入缴费流水
     *
     * @param int $year
     * @param int $userId
     * @param float $received
     * @param int $time
     * @param int $type
     * @param array $extra
     * @throws XhException
     *
     * create by ck 20180914
     * modify by ck 20181022    判断流水号是否已存在，有则跳过
     */
    public static function importFlow(int $year, int $userId, float $received, int $time, int $type, array $extra = [])
    {
        if ($received <= 0) {
            throw new XhException('应缴需大于0');
        }
        $db = Main::getDB();
        try {
            $db->begin();
            $flow = new CostChargeFlow(array_merge([
                'year' => $year,
                'userId' => $userId,
                'receiveNum' => $received,
                'receiveTime' => $time,
                'sourceType' => $type
            ], $extra));

            //判断流水号是否已存在
            if ($flow->sourceNo) {
                $exist = CostChargeFlow::count([
                    'conditions' => 'bDelete = 0 AND sourceNo = :sourceNo:',
                    'bind' => ['sourceNo' => $flow->sourceNo]
                ]);
                if ($exist) {
                    throw new XhException('流水号已存在', '无需处理', 200);
                }
            }

            //处理总表
            $charge = CostCharge::getInitObj($year, $userId);
            $charge->received += $received;
            $charge->flowNum++;

            if (!$charge->save()) {
                throw new XhException('保存失败：' . $charge->getError());
            }
            if (!$flow->save()) {
                throw new XhException('流水保存失败：' . $flow->getError());
            }
            $db->commit();
            unset($flow, $charge, $db);
        } catch (XhException $e) {
            $db->rollback();
            if ($e->getCode() != 200) {
                throw new XhException($e->getMessage(), $e->getTrace());
            }
        }
    }

    /**
     * 删除应缴记录
     *
     * @param array $ids
     * @throws XhException
     *
     * create by ck 20180918
     * modify by ck 20180920    更新学生服务到期时间
     */
    public static function delDetail(array $ids)
    {
        $db = Main::getDB();
        try {
            $db->begin();
            $details = CostChargeDetail::find([
                'conditions' => 'id IN ({ids:array}) AND bDelete = 0',
                'bind' => ['ids' => $ids]
            ]);

            //删除并处理总表数据
            foreach ($details as $detail) {
                $detail->bDelete = 1;

                $charge = CostCharge::getInitObj($detail->year, $detail->userId);
                $charge->receivable -= $detail->receivable;
                $charge->chargeNum--;

                if (!$detail->save()) {
                    throw new XhException('保存失败：' . $detail->getError());
                }
                if (!$charge->save()) {
                    throw new XhException('保存失败：' . $charge->getError());
                }

                //更新服务到期时间
                $stud = XhsysUserstud::getInitObj($detail->userId);
                if ($detail->serviceEnd == $stud->iExpireTime) {
                    $maxTime = CostChargeDetail::maximum([
                        'column' => 'serviceEnd',
                        'conditions' => 'bDelete = 0 AND userId = :userId:',
                        'bind' => ['userId' => $detail->userId]
                    ]);
                    if ($stud->iExpireTime != $maxTime) {
                        $stud->iExpireTime = $maxTime ?: 0;
                        if (!$stud->save()) {
                            throw new XhException('学生保存失败：' . $stud->getError());
                        }
                    }
                }
            }
            $db->commit();
        } catch (XhException $e) {
            $db->rollback();
            throw new XhException('删除失败', $e->getMessage());
        }
    }

    /**
     * 删除流水记录
     *
     * @param array $ids
     * @throws XhException
     *
     * create by ck 20180918
     */
    public static function delFlow(array $ids)
    {
        $db = Main::getDB();
        try {
            $db->begin();
            $flows = CostChargeFlow::find([
                'conditions' => 'id IN ({ids:array}) AND bDelete = 0',
                'bind' => ['ids' => $ids]
            ]);

            //删除并处理总表数据
            foreach ($flows as $flow) {
                $flow->bDelete = 1;

                $charge = CostCharge::getInitObj($flow->year, $flow->userId);
                $charge->received -= $flow->receiveNum;
                $charge->flowNum--;

                if (!$flow->save()) {
                    throw new XhException('保存失败：' . $flow->getError());
                }
                if (!$charge->save()) {
                    throw new XhException('保存失败：' . $charge->getError());
                }
            }
            $db->commit();
        } catch (XhException $e) {
            $db->rollback();
            throw new XhException('删除失败', $e->getMessage());
        }
    }

    /**
     * 获取学生基本信息
     *
     * @param $userId
     * @return XhsysUser|\Phalcon\Mvc\Model
     *
     * create by sqb 20190104
     */
    public static function getUserInfo($userId)
    {
        $userOjb = XhsysUser::findFirst($userId);

        return $userOjb;
    }

    /**
     * 获取学校基本信息
     *
     * @param $schoolId
     * @return XhschoolInfo
     *
     * create by sqb 20190104
     */
    public static function getSchoolInfo($schoolId)
    {
        $schoolObj = XhschoolInfo::findFirst($schoolId);

        return $schoolObj;
    }
}
